<template>
  <div>
    <el-dialog
      title="编辑产品"
      :visible.sync="dialogVisible"
      width="1100px">
      <el-form :model="customerForm" size="mini" label-width="130px" :rules="rules" ref="customerForm">
        <div class="table-container" style="margin-top:0">
        <el-table :data="customerForm.useGoods" border style="width: 100%;margin:20px 0">
          <el-table-column
            width="150"
            align="center"
            label="品类">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.categoryId`" :rules="rules.categoryId">
                <el-cascader
                  :key="categoryIdKey"
                  filterable
                  :filter-method="filterMethod"
                  :ref="'category'+scope.$index"
                  @change="changeCategoryId(scope.$index,scope.row)"
                  :options="categoryList" clearable v-model="scope.row.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            label="牌号">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.goodsSnId`" :rules="rules.goodsSnId">
                <el-select
                  multiple
                  v-model="scope.row.goodsSnId"
                  filterable
                  placeholder="请选择/输入厂家牌号"
                  clearable>
                  <el-option
                    v-for="(item,index) in goodsList[scope.$index]"
                    :key="index"
                    :label="item.brandName+'/'+item.goodsSn"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="月使用量"
            width="150"
            align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.monthUseNum`" :rules="rules.monthUseNum">
                    <el-input type="number" v-model="scope.row.monthUseNum" clearable></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            label="替换牌号">
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-select
                  v-model="scope.row.replaceGoodsSnId"
                  filterable
                  multiple
                  placeholder="请选择/输入厂家牌号"
                  clearable>
                  <el-option
                    v-for="(item,index) in goodsList[scope.$index]"
                    :key="index"
                    :label="item.brandName+'/'+item.goodsSn"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column  label="采购渠道" width="150" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`useGoods.${scope.$index}.supplierName`" :rules="rules.supplierName">
                <el-select v-model="scope.row.supplierName" clearable  multiple>
                  <el-option label="聚合厂" value="聚合厂"></el-option>
                  <el-option label="贸易商" value="贸易商"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            header-align="center"
            width="260"
            label="竞对名称">
            <template slot-scope="scope">
              <el-tag
                style="margin-bottom:5px;margin-right:5px"
                size="small"
                v-for="(tag,index) in scope.row.competitor"
                :key="tag"
                closable
                @close="delCompetitor(scope.$index,index)">
                {{tag}}
              </el-tag>
              <el-button  class="button-new-tag" size="mini" @click="addCompetitor(scope.$index)">+ 添加</el-button>
            </template>
          </el-table-column>


          <el-table-column  label="操作" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="delUseGoods(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="small" @click="addUseGoods">增加产品信息</el-button>
      </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="btnOk" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="添加竞对"
      :visible.sync="dialogVisible2"
      width="360px">
      <el-input v-model.trim="businessCode" @blur="seachRepeat" clearable  placeholder="请输入竞对信用码"></el-input>
      <div style="font-weight: bold;font-size: 14px;padding-top: 20px;">自动匹配抬头：{{companyName}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="sumbitname">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>

import store from '@/store'
import {getBrandAndGoodsSn, getCategoryList,editUseGoods,useGoodsList} from '@/api/company';
import {getCompanyInfo} from '@/api/partner';
import { mapGetters } from 'vuex'
const defeaultGoodLineItem = {//新增产品信息
  ugId:'',//id（编辑用）
  categoryId:'',//产品线id
  goodsSn:'',//牌号
  monthUseNum:'',//月使用量
  supplierName:[],//采购渠道
  goodsSnId:[],
  categoryName:'',
  replaceGoodsSnId:[],
  competitor:[]
};
const defaultCustomerForm = {
  customerId: '',//客户名称
  useGoods: [],//产品信息列表
};

export default {
  name: "addUseGoods",
  data(){
    const isvalidateCompetitor = (rule, value, callback)=> {
      let indexArray = rule.field.split(".");
      let i = indexArray[1];
      if (this.customerForm.useGoods[i].supplierName == '竞争对手' && !value) {
        callback(new Error('请输入竞对名称'))
      }else{
        callback()
      }
    };
    const isvalidateSupplierName = (rule, value, callback)=> {
      let indexArray = rule.field.split(".");
      let i = indexArray[1];
      if (!this.isZCustomer && value.length == 0) {
        callback(new Error('此项必填'))
      }else{
        callback()
      }
    };
    return {
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      dialogVisible:false,
      customerForm: JSON.parse(JSON.stringify(defaultCustomerForm)),
      categoryList:[],
      goodsList:[],//牌号
      btnLoading:false,
      rules:{
        categoryId:[{required: true, trigger: 'change' ,message: '此项必填',}],
        goodsSnId:[{required: true, trigger: 'change' ,message: '此项必填',}],
        monthUseNum:[{required: true, trigger: 'blur' ,message: '此项必填',}],
        supplierName:[{required: true, trigger: 'change' ,validator: isvalidateSupplierName}],
        competitor:[{required: true, trigger: 'change' ,validator: isvalidateCompetitor}],

      },
      categoryIdKey:1,
      isZCustomer:'',
      companyName:'',
      businessCode:'',
      dialogVisible2:false,
      cutIndex:''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  created() {

  },
  filters: {

  },

  components : {

  },
  methods: {
    filterMethod(node, keyword){
      let text = node.text.toLowerCase();
      let val = keyword.toLowerCase();
      return text.includes(val)
    },
    sumbitname(){
      if(this.companyName == ''){
         this.$message.error('抬头没有匹配')
         return false
      }
      this.customerForm.useGoods[this.cutIndex].competitor.push(this.companyName)
      this.dialogVisible2 = false
    },
    seachRepeat() {
      getCompanyInfo({businessCode:this.businessCode}).then((companyInfo) => {
        this.companyName = companyInfo.companyName;
        if(companyInfo.companyName == ''){
          this.businessCode = '';
        }
      }).catch(() => {
        this.businessCode = '';
      })
    },
    delCompetitor(i,ii){
     this.customerForm.useGoods[i].competitor.splice(ii,1)
    },
    addCompetitor(i){
      this.cutIndex = i
      this.businessCode = ''
      this.companyName = ''
      this.dialogVisible2 = true
    },
    getCustomerOption(){
      useGoodsList({customerId:this.customerForm.customerId}).then((res)=>{
        res.list.forEach((el,index)=>{
          let c = {}
          for(let key in defeaultGoodLineItem){
            c[key] = el[key] ? el[key] : defeaultGoodLineItem[key]
          }
          this.customerForm.useGoods.push(c)
          this.goodsList.push([])
          if(c.categoryId){
            this.getOrderGoodsList(c,index);
          }

        })
        this.isZCustomer = res.isZCustomer
      })
    },
    showPop(customerId){
      this.dialogVisible = true;
      this.customerForm = JSON.parse(JSON.stringify(defaultCustomerForm))
      this.goodsList = []
      this.customerForm.customerId = customerId
      this.getcategoryListFn()
      this.getCustomerOption()
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false;
    },
    // 提交
    btnOk() {
      this.$refs.customerForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          editUseGoods(this.customerForm).then(()=>{
            this.btnLoading = false
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.handleClose();
            this.$emit('update')
          }).catch(()=>{
            this.btnLoading = false
          })

        } else {
          return false;
        }
      })
    },
    //删除产品信息
    delUseGoods(index) {
      this.customerForm.useGoods.splice(index, 1)
    },
    //新增产品信息
    addUseGoods() {
      this.customerForm.useGoods.push(JSON.parse(JSON.stringify(defeaultGoodLineItem)))
    },

    //获取品类列表
    getcategoryListFn(){
      getCategoryList().then((res)=>{
        this.categoryList = res.list
      })
    },
    //切换品类
    changeCategoryId(index, row){
      let chooseList = this.customerForm.useGoods.filter((el)=>{
        return this.customerForm.useGoods[index].categoryId == el.categoryId
      })
      if(chooseList.length > 1){
        let c = JSON.parse(JSON.stringify(this.customerForm.useGoods[index]))
        c.categoryId = ''
        c.categoryName = ''
        c.goodsSnId = [];
        c.replaceGoodsSnId = []
        this.customerForm.useGoods.splice(index,1,c)
        this.$nextTick(()=>{
          this.categoryIdKey = this.categoryIdKey+1
        })
        this.$message({
          type: "error",
          message: "品类已存在!",
        });
        return
      }
      this.customerForm.useGoods[index].categoryId = row.categoryId;
      this.$nextTick(()=>{
        this.customerForm.useGoods[index].categoryName = this.$refs['category'+index].getCheckedNodes()[0] ? this.$refs['category'+index].getCheckedNodes()[0]['label'] : ''
      })
      this.customerForm.useGoods[index].goodsSnId = [];
      this.customerForm.useGoods[index].replaceGoodsSnId = []
      this.getOrderGoodsList(row,index);
    },
    // 获取牌号列表
    getOrderGoodsList(row,index){
      if(row.categoryId){
        getBrandAndGoodsSn({
          categoryId:row.categoryId
        }).then((res)=>{
          this.goodsList.splice(index,1,res.list)
          console.log(index)
          console.log(this.goodsList)
          // this.goodsList = res.list
        })
      }
    },
  },
}
</script>




